package com.example.myapplication.acticity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.FileUtils;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.content.FileProvider;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.MapView;
import com.example.myapplication.ContactsActivity;
import com.example.myapplication.FileUtil;
import com.example.myapplication.MyApp;
import com.example.myapplication.R;
import com.example.myapplication.ToastUtil;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LoginActivity extends AppCompatActivity {
    private AppCompatEditText mobileEditText;
    private AppCompatEditText passwordEditText;
    private AppCompatButton loginButton;
    private AppCompatButton xaingcheAppCompatButton;
    private AppCompatButton chanAppCompatButton;
    private AppCompatButton chan11AppCompatButton;
    private AppCompatButton chan1AppCompatButton;
    private AppCompatButton chan2AppCompatButton;
    private ImageView tupianImageView;
    private File file;
    private VideoView mainVideoView;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();

    private MapView bmapView;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.kong1);

        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数

        bmapView.getMap().setMyLocationEnabled(true);



        mobileEditText = findViewById(R.id.mobileEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        loginButton = findViewById(R.id.loginButton);
        xaingcheAppCompatButton = findViewById(R.id.xaingcheAppCompatButton);
        chanAppCompatButton = findViewById(R.id.chanAppCompatButton);
        chan11AppCompatButton = findViewById(R.id.chan11AppCompatButton);
        chan1AppCompatButton = findViewById(R.id.chan1AppCompatButton);
        chan2AppCompatButton = findViewById(R.id.chan2AppCompatButton);
        tupianImageView = findViewById(R.id.tupianImageView);
        mainVideoView = findViewById(R.id.mainVideoView);

        bmapView=findViewById(R.id.bmapView);

        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);

        option.setCoorType("bd09ll");

        option.setScanSpan(1000);

        option.setOpenGps(true);

        option.setLocationNotify(true);

        option.setIgnoreKillProcess(false);

        option.SetIgnoreCacheException(false);

        option.setWifiCacheTimeOut(5 * 60 * 1000);

        option.setEnableSimulateGps(false);

        option.setNeedNewVersionRgc(true);

        option.setIsNeedAddress(true);

        option.setNeedNewVersionRgc(true);

        mLocationClient.setLocOption(option);


        mLocationClient.setLocOption(option);
        mLocationClient.start();

        /*
        ArrayList<String> files=getFilesAllName("sdcard/Movies");
        for (int i=0;i<files.size();i++)
        {
            if (files.get(i).contains(".mp4")){
                File file=new File(files.get(i));
                mainVideoView.setVideoURI(Uri.fromFile(file));
                mainVideoView.start();
                break;
            }
        }
        */

        String key = MyApp.get().getSharedPreferences().getString("key", "");
        if (!key.isEmpty()) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }

        loginButton.setOnClickListener(v ->
        {
            String Name = mobileEditText.getText().toString();
            String password = passwordEditText.getText().toString();

            if (Name.isEmpty()) {
                Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!isMobileNO(Name)) {
                Toast.makeText(this, "请输入有效的手机号码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.isEmpty()) {
                Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.length() < 6) {
                Toast.makeText(this, "请输入有效的密码", Toast.LENGTH_SHORT).show();
                return;
            }


            OkGo.<String>post("https://demo.shopwt.com/api/mobile/index.php?w=login")
                    .params("username", Name)
                    .params("passwork", Name)
                    .params("client", "wap")
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body().toString());
                                if (jsonObject.getInt("code") == 400) {
                                    jsonObject = jsonObject.getJSONObject("datas");
                                    ToastUtil.show(LoginActivity.this, jsonObject.getString("error"));
                                    return;
                                }
                                jsonObject = jsonObject.getJSONObject("datas");
                                String key = jsonObject.getString("key");
                                MyApp.get().getEditor().putString("key", key).apply();
                                ToastUtil.show(LoginActivity.this, "登录成功~");
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        });

        xaingcheAppCompatButton.setOnClickListener(v -> {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 999);
        });


        chanAppCompatButton.setOnClickListener(view -> {
            file = FileUtil.createFile(
                    getExternalMediaDirs()[0].getAbsolutePath(),
                    "learn2",
                    "jpg"
            );
            if (file != null) {
                Uri uri = FileProvider.getUriForFile(this, "com.example.myapplication.fileProvider", file);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, 1000);
            }
        });

        chan1AppCompatButton.setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(intent, 1500);
        });

        chan2AppCompatButton.setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("video/*");
            startActivityForResult(intent, 1600);
        });

        //打开相机录制视频并播放
        chan11AppCompatButton.setOnClickListener(v -> {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 1700);
        });


    }


    public boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    @Override
    protected void onPause() {
        super.onPause();
        bmapView.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bmapView.onDestroy();

    }

    @Override
    protected void onResume() {
        super.onResume();
        bmapView.onResume();



        XXPermissions.with(this).permission(getPermissionsl()).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {
                //用户允许权限申请

            }

            @Override
            public void onDenied(List<String> permissions, boolean never) {
                //用户拒绝了权限申请

            }
        });
    }

    public String[] getPermissionsl() {

        return new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_EXTERNAL_STORAGE,//读外部存储
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//写外部存储
                Manifest.permission.CAMERA,//拍照权限
        };
    }


    private ArrayList<String> getFilesAllName(String path) {
        File file = new File((path));
        File[] files = file.listFiles();
        if (files == null) {
            return null;
        }
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            list.add(files[i].getAbsolutePath());
        }
        return list;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 999) {
                Bitmap bitmap = data.getExtras().getParcelable("data");
                tupianImageView.setImageBitmap(bitmap);
            }

            if (requestCode == 1000) {
                Log.d("TAGS", file.getAbsolutePath());
                tupianImageView.setImageURI(Uri.fromFile(file));
            }

            if (requestCode == 1500) {
                file = FileUtil.createFile(
                        getExternalMediaDirs()[0].getAbsolutePath(),
                        "learn2",
                        "jpg"
                );

                Intent cropIntent = new Intent("com.android.camera.action.CROP");//跳到系统裁剪界面
                cropIntent.setDataAndType(data.getData(), "image/*");//设置裁剪图片的数据源
                cropIntent.putExtra("crop", "true");//设置裁剪
                cropIntent.putExtra("aspectX", 2);
                cropIntent.putExtra("aspectY", 1);
                cropIntent.putExtra("outputX", 500);
                cropIntent.putExtra("outputY", 500);
                cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + file.getAbsolutePath()));
                cropIntent.putExtra("return-data", "false");
                startActivityForResult(cropIntent, 2000);
                FileUtil.showInAlbum(this, file.getAbsolutePath());
            }

            if (requestCode == 2000) {
                tupianImageView.setImageURI(Uri.fromFile(file));
            }

            if (requestCode == 1600) {
                Uri uri = data.getData();
                mainVideoView.setVideoURI(uri);
                mainVideoView.start();
            }

            if (requestCode == 1700) {
                Uri uri = data.getData();
                mainVideoView.setVideoURI(uri);
                mainVideoView.start();
            }

        }
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {


            double latitude = location.getLatitude();    //获取纬度信息
            double longitude = location.getLongitude();    //获取经度信息
            float radius = location.getRadius();    //获取定位精度，默认值为0.0f

            String coorType = location.getCoorType();

            String addr = location.getAddrStr();    //获取详细地址信息
            String country = location.getCountry();    //获取国家
            String province = location.getProvince();    //获取省份
            String city = location.getCity();    //获取城市
            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息
            String adcode = location.getAdCode();    //获取adcode
            String town = location.getTown();    //获取乡镇信息
//
            int errorCode = location.getLocType();
            Log.d("TAGS", latitude + "|" + longitude);
            Log.d("TAGS", addr + "|" + longitude+"|"+country+"|"+province+"|"+city+"|"+district+"|"+street+"|"+adcode+"|"+town);

        }
    }

}
